package com.huang.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.huang.annotation.Sensitive;
import com.huang.enums.SensitiveStrategy;

import java.io.IOException;
import java.util.Objects;

/**
 * 脱敏json配置
 *
 * @author han
 * @since 2022-06-21 16:49:19
 */
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveStrategy sensitiveStrategy;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(sensitiveStrategy.desensitize().apply(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Sensitive sensitive = property.getAnnotation(Sensitive.class);
        if (Objects.nonNull(sensitive) && Objects.equals(String.class, property.getType().getRawClass())) {
            this.sensitiveStrategy = sensitive.strategy();
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
